﻿if (typeof Modules == "undefined") Modules = {};

Modules.Resource = {
    Container: '',
    CatID: '',
    ID: '',

    ResourceViewPage: '#content-page',
    ResourceViewID: '#resource-id',
    ResourceViewCat: '#resource-cat',
    ResourceViewHome: '#resource-home',
    ResourceViewList: '.resource-list',
    $Resource: [],

    init: function (container) {
        var _this = this;
        //set variable(s)
        _this.Container = container || _this.ResourceViewPage;
        _this.ID = Modules.Core.QueryString.ID();
        _this.CatID = Modules.Core.QueryString.CatID();
        //read view html
        _this.load();
    },
    load: function () {
        var _this = this;
        if (_this.Container) {
            $(_this.Container).html('');
            _this.loadView(function (data) {
                if (data) {
                    //luu lai resource element 
                    _this.$Resource = $(data);
                    //chay theo ID
                    if (_this.ID != null && _this.ID != '') {
                        _this.loadDetail(_this.ID);
                    }
                    //chay theo CAT
                    else if (_this.CatID != null && _this.CatID != '') {
                        var rowInPage = Modules.Core.QueryString.RowInPage() || 100,
                        pageIndex = Modules.Core.QueryString.PageIndex() || 1;
                        _this.loadList(_this.CatID, rowInPage, pageIndex);
                    }
                    //chay default
                    else {
                        _this.loadList();
                    }
                }
            });
        }
    },
    loadView: function (callback) {
        var template = Modules.Core.CoreFunction.getTemplateView(),
            url = template + '/view/resource.htm'
        $.ajax({
            url: url,
            success: function (data) {
                callback(data);
            },
            error: function () {
                console.log('resource view not exist!!!');
            }
        });
    },
    //-----------------------home, cat----------------------------//
    loadList: function (catID, rowInPage, pageIndex) {
        var _this = this,
            view = _this.ResourceViewHome,
            resourceView = Modules.Layout.getResourceView(),
            ext = '',
            coref = Modules.Core.CoreFunction;
        //chay theo CAT
        if (catID) {
            ext = ' ID="' + catID + '"';
            view = _this.ResourceViewCat;
        }
        //get input data
        var $view = _this.$Resource.find(view),
            $list = _this.$Resource.find(view + '-' + resourceView),
            $detail = $list.find('.detail'),

            inputValue = coref.getDataInput($view),
            inputDetail = coref.getDataInput($list.find('.detail ul')),
            detailTemplate = $detail.find('ul').html();

        if (typeof (inputValue) == 'undefined') {
            console.log('parameter run is null ');
            return;
        }
        $(this.Container).append($view);
        //build input cat(s)
        inputValue = coref.getInputValue($.string.Format(inputValue + ext, Modules.Layout.Type));
        inputDetail = coref.getInputValue(inputDetail);

        if (typeof (inputDetail) == 'undefined') {
            console.log('detail parameter run is null ');
        }
        //get data
        Modules.ServiceData.GetContextData(inputValue, function (data) {
            if (data[1].length > 0) {
                //dung de luu list element
                var aList = [];
                //header                
                _this.showList(data[1], $view, $list, aList);
                //detail
                if (typeof rowInPage == 'undefined' || rowInPage == '') {
                    rowInPage = 6;
                }
                if (typeof pageIndex == 'undefined' || pageIndex == '') {
                    pageIndex = 1;
                }
                //build input detail
                var aInput = [];
                for (var i = 0; i < data[1].length; i++) {
                    var it = data[1][i];
                    if (it && it.IDKey) {
                        aInput.push($.string.Format(inputDetail, it.IDKey, rowInPage, pageIndex));
                    }
                }
                if (aInput.length) {
                    //top item detail
                    Modules.ServiceData.GetContextData(aInput.join(''), function (detail) {
                        if (detail) {
                            for (var j = 1; j < detail.length; j++) {
                                if (detail[j].length) {
                                    _this.showListDetail(detail[j], detailTemplate, aList[j - 1]);
                                }
                            }
                        }
                    });
                }
            }
        });
    },
    showList: function (data, $view, $list, aList) {
        var aHeader = [];
        for (var i = 0; i < data.length; i++) {
            var it = data[i],
                $tlist = $list.clone(),
            header = $tlist.find('.header').html();
            //replace tham so va add vao control
            if (it && it.IDKey) {
                $tlist.find('.header').html(Modules.Core.View.getReplace(header, it));
                $tlist.find('ul').attr({ 'id': it.IDKey }).html('');
                aList.push($tlist);
                $view.append($tlist);
            }
        }
    },
    showListDetail: function (detail, template, $list) {
        var aItem = [],
            parentID = '';
        for (var i = 0; i < detail.length; i++) {
            var it = detail[i];
            if (parentID == '') parentID = it.ParentKey;
            aItem.push(Modules.Core.View.getReplace(template, it));
        }
        if ($list.length) {
            $list.find('ul').html(aItem.join(''));
            Modules.Core.View.initImage($list);
        }
    },
    //-----------------------id----------------------------//
    loadDetail: function (ID) {
        var _this = this,
            coref = Modules.Core.CoreFunction,
            view = _this.ResourceViewID,
            resourceView = Modules.Layout.getResourceView();

        var $view = _this.$Resource.find(view),
            $detail = _this.$Resource.find(view + '-' + resourceView),
            $nav = $detail.find('.resource-nav');
        var inputValue = '',
            inputTemplate = coref.getDataInput($view),
            aInputData = [],
            aEl = [];
        var step = 1;
        //get info cat
        if (_this.CatID) {
            step = 2;
            inputValue += $.string.Format(coref.getInputValue(coref.getDataInput($detail.find('.resource-nav ul'))), _this.CatID, ID);
        }
        //get info id
        inputValue += $.string.Format(coref.getInputValue(inputTemplate), Modules.Layout.Type, ID);
        aEl.push($detail.find('.resource-view'));
        //get info data
        $detail.find('[' + Modules.Core.Default.Input + ']').each(function (idx, it) {
            var $el = $(it);
            aEl.push($el);
            aInputData.push($.string.Format(coref.getInputValue(coref.getDataInput($el)), ID));
        });

        inputValue += aInputData.join('');

        $detail.appendTo($view);
        $(this.Container).append($view);

        Modules.ServiceData.GetContextData(inputValue, function (data) {
            if (data) {
                if ($nav.length) {
                    var navdata = [data[1]];
                    if (step == 2) {
                        navdata.push([data[2][0]]);
                    }
                    _this.showDetailNav(navdata, $nav);
                }
                _this.showDetail(data, aEl, step);
            }
        });
    },
    showDetailNav: function (data, $nav) {
        if (data) {
            var adata = [{ LinkURL: Modules.Layout.homeLink(), Name: 'Trang chủ', Level: '1'}];
            for (var i = 0; i < data.length; i++) {
                if (data[i].length > 1) {
                    for (var j = 0; j < data[i].length; j++) {
                        var ij = data[i][j];
                        ij.Level = '1';
                        ij.LinkURL = $.string.Format('?Type={0}&CatID={1}', ij.Type, ij.IDKey);
                        adata.push(ij);
                    }
                }
                else {
                    var it = data[i][0];
                    it.Level = '1';
                    adata.push(it);
                }
            }
            Modules.Core.View.init($nav.find('ul'), adata);
        }
    },
    showDetail: function (data, aEl, step) {
        for (var i = 0; i < aEl.length; i++) {
            if (aEl[i].hasClass('slogan')) {
                aEl[i] = $('.resource-view .slogan');
            }
            Modules.Core.View.init(aEl[i], data[i + step]);
            //kiem tra them image
            Modules.Core.View.initImage(aEl[i]);
        }
    }
    //---------------------------------------------------//
};

function initResource(container) {
    Modules.Resource.init(container);
};

function reloadResource(options) {
    var thisObj = Modules.Resource;
    //reset
    thisObj.CatID = "";
    thisObj.ID = "";

    if (options) {
        if (options.CatID) {
            thisObj.CatID = options.CatID;
        }
        if (options.ID) {
            thisObj.ID = options.ID;
        }
    }
    thisObj.load();
};
